<?php
namespace JaPhIM\lib\db;

use Medoo\Medoo;

class DbPool
{

    protected $pool;
    protected $config;

    public function __construct($size)
    {
        $this->pool = new \Swoole\Coroutine\Channel($size);
        $this->config = require __DIR__.'/../../../config.php';
        for ($i = 0;$i < $size; $i++){
            while (true){
                try {
                    $dbh = new Medoo($this->config['database']);
                    $this->put($dbh);
                    break;
                }catch (\PDOException $e){
                    echo $e->getMessage();
                    usleep(1*1000);
                    continue;
                }
            }
        }
    }

    public function get()
    {
        return $this->pool->pop();
    }

    public function put(\Medoo\Medoo $dbh)
    {
        $this->pool->push($dbh);
    }

    public function close()
    {
        $this->pool = null;
    }

}